package com.aolong.archives.core.sysmanage.dao.impl;

import java.util.HashMap;
import java.util.Map;

import com.aolong.archives.common.util.Const;
import com.aolong.archives.core.sysmanage.dao.IUserDao;
import com.aolong.archives.core.sysmanage.entity.UserEntity;
import com.rock.platform.dao.BaseDao;
import com.rock.platform.entity.ActionParamsEntity;
import com.rock.platform.entity.PageEntity;

public class UserDao extends BaseDao implements IUserDao{

	public UserEntity findByLoginName(String loginName)
	{
		String strSql = "select * from TSM_User where loginname =:loginName";
		Map<String,Object> paras = new HashMap<String,Object>();
		paras.put("loginName", loginName);
		return super.getSingleResult(strSql, UserEntity.class, paras);
	}

	public PageEntity findAll(ActionParamsEntity actionParams) {
		
		String strSql = "select u.* from TSM_User u";
		actionParams.replaceField("statusDesc", "status").addSort("loginName");
		return super.getPageEntity(strSql, actionParams, UserEntity.class);
	}
	
	public int disabled(Object[] ids) {
		this.updateValue("status", Const.Status.DISABLED.toValue() , ids);
		return 0;
	}

	public int activate(Object[] ids) {
		this.updateValue("status", Const.Status.NORMAL.toValue(), ids);
		return 0;
	}

	public int remove(Object[] ids) {
		String strSql = "delete TSM_User  where userId = :id";
		Map<String,Object> params = new HashMap<String,Object>();
		for(Object id : ids)
		{
			params.clear();
			params.put("id", id);
			super.execute(strSql, params);
		}
		return 0;
	}

	private int updateValue(String fieldName,Object fieldValue,Object[] ids)
	{
		StringBuffer sbSql = new StringBuffer();
		sbSql.append("update TSM_User set ");
		sbSql.append(fieldName);
		sbSql.append(" = :val where userId = :id" );
		Map<String,Object> params = new HashMap<String,Object>();
		for(Object id : ids)
		{
			params.clear();
			params.put("val", fieldValue);
			params.put("id", id);
			super.execute(sbSql.toString(), params);
		}
		return 0;
	}

	public int modifyPassword(String password, String id) {
		
		Object[] ids = {id};
		return this.updateValue("password",password,ids);
	}

	public int resetPassword(String password, Object[] ids) {
		return this.updateValue("password",password,ids);
	}

	public PageEntity findByRoleId(String roleId, ActionParamsEntity actionParams) {
		String strSql = "select u.* from TSM_User u " 
						+ " where u.userId in (select userId from TSM_RoleUser where roleId = :roleId)";
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("roleId", roleId);
		actionParams.addSort("userCode");
		return super.getPageEntity(strSql, actionParams, UserEntity.class, params);
	}
}
